<?php

namespace frontend\models;

use backend\models\GroupMember;
use common\helps\tools;
use frontend\models\Comment as comment_model;
use frontend\models\PostsCollect as p_collect_model;
use Yii;
use yii\db\ActiveRecord;
use yii\behaviors\TimestampBehavior;
use yii\db\Exception;
use yii\db\Query;

/**
 * This is the model class for table "NewProject".
 *
 */
class NewProject extends ActiveRecord
{

    public $type;
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%new_project}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return[
            [['title','tags','area','movie_time','release_time','pic','introduction','advertisement','policy','theme','market','case','background_img'], 'trim'],
            [['title','class_id','tags','area','pic','introduction','advertisement','background_img'], 'required', 'message'=>'{attribute}不能为空'],
            [['id','type','class_id','status','is_recommend'], 'match', 'pattern' => '/^[1-9][0-9]*$/','message'=>'{attribute}值无效'],
        ];
    }


    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => '项目id',
            'title' => '项目名称',
            'class_id'=>'项目分类',
            'tags'=>'类型标签',
            'area'=>'地区',
            'movie_time'=>'片长',
            'release_time'=>'上映时间',
            'pic'=>'封面图',
            'background_img'=>'背景图',
            'status'=>'项目状态',
            'is_recommend'=>'项目是否推荐',
            'introduction'=>'项目简介',
            'advertisement'=>'宣发计划',
            'policy'=>'政策优势',
            'theme'=>'题材优势',
            'market'=>'市场优势',
            'case'=>'相关案例',
            'join_num'=>'参与人数',
            'type'=>'操作类型',
        ];
    }


    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            TimestampBehavior::className(),
        ];
    }


    /**
     * 获取项目列表
     * @param $params
     * @author hey_heyang(635870453@qq.com)
     * @return array
     */
    public function getProjectList($params){
        $condition = ['and','new_project.status=1',['is_recommend'=>1],['new_project.deleted_at'=>null]];
        $list = (new Query())
            ->select('new_project.id,
                    new_project.pic,
                    new_project.title ,
                    new_project.is_recommend,
                    new_project.introduction,
                    new_project.click_num,
                    project_class.title as class_name,
                    FROM_UNIXTIME(new_project.created_at) as created_at'
                    )
            ->from('new_project')
            ->leftJoin('project_class','project_class.id=new_project.class_id')
            ->where($condition)
            ->orderBy('new_project.id desc')
            ->all();
        if(count($list)){
            $actor_model = new ProjectActor();
            foreach($list as &$value){
                $actor_list =$actor_model->find()->select('*')->where(['project_id'=>$value['id'],'deleted_at'=>null])->asArray()->all();
                $value['actor_list'] = $actor_list;
            }
        }
        return empty($list)?array():$list;

    }


    /**
     * 获取项目详情
     * @param $params
     * @param $member_info
     * @author hey_heyang(635870453@qq.com)
     * @return array
     */
    public function getProjectInfo($params,$member_info){
        $condition = ['new_project.deleted_at'=>null,'new_project.status'=>1,'new_project.id'=>intval($params['project_id'])];
        $list =
            (new Query())->select(
            'new_project.*,FROM_UNIXTIME(new_project.release_time) as release_time,
            project_class.title as class_name,
            FROM_UNIXTIME(new_project.created_at) as created_at'
            )
            ->from('new_project')
            ->leftJoin('project_class','project_class.id=new_project.class_id')
            ->where($condition)
            ->one();
        if(count($list)){
            $tags_model = new ProjectType();
            $tags = unserialize($list['tags']);
            $list['tags'] =$tags_model->find()->select('title')->where(['in','id',$tags])->asArray()->all(); //项目标签类型
//            $actor_model = new ProjectActor();
//            $tags_model = new ProjectType();
//            $video_model = new ProjectVideo();
//            $pic_model = new ProjectPicture();
//            $information = new Information();
//            $actor_list =$actor_model->find()->select('*')->where(['project_id'=>$params['project_id'],'deleted_at'=>null])->asArray()->all();
//            $list['actor_list'] = $actor_list; //项目演职人员

//            $list['video_list'] = $video_model->find()->select('*')->where(['project_id'=>$params['project_id'],'deleted_at'=>null])->asArray()->all();//项目视频
//            $list['pic_list'] = $pic_model->find()->select('*')->where(['project_id'=>$params['project_id'],'deleted_at'=>null])->asArray()->all();//项目海报
//            $list['information_list'] = $information->find()->select('*')->where(['project_id'=>$params['project_id'],'deleted_at'=>null,'status'=>1])->asArray()->all();//项目相关资讯动态
//            $list['information_list_num'] = count($list['information_list']);
            static::updateAllCounters(['click_num' => 1], ['id' =>intval($params['project_id'])]); //自增查看数量

        }
        return empty($list)?array():$list;

    }

    /**
     * 获取项目是否收藏
     * @param $params
     * @param $member_info
     * @author hey_heyang(635870453@qq.com)
     * @return array
     */
    public function getICollectProject($params,$member_info){
        $collect_model = new PostsCollect();
        if(!empty($member_info['id'])){
            $collect = $collect_model->find()->where(['item_id'=>intval($params['project_id']),'member_id'=>$member_info['id']])->asArray()->one();
            if(empty($collect) || $collect['is_collect']==2){ //未收藏
                $list['is_collect']=2;
            }else{
                $list['is_collect']=1; //已收藏
            }
        }
        return empty($list)?array():$list;

    }


    /**
     * 获取项目演职人员信息
     * @param $params
     * @author hey_heyang(635870453@qq.com)
     * @return array
     */
    public function getProjectActorInfo($params){
        $actor_model = new ProjectActor();
        $actor_list =$actor_model->find()->select('*')->where(['project_id'=>$params['project_id'],'deleted_at'=>null])->orderBy('sort ASC')->asArray()->all();
        return empty($actor_list)?array():$actor_list;

    }


    /**
     * 获取项目分类列表
     * @author hey_heyang(635870453@qq.com)
     * @return array
     */
    public function getProjectClassList(){
        $class_model = new ProjectClass();
        $list =$class_model->find()->select('*')->where(['status'=>1,'deleted_at'=>null])->orderBy('sort ASC')->asArray()->all();
        return empty($list)?array():$list;

    }



    /**
     * 获取项目海报
     * @param $params
     * @author hey_heyang(635870453@qq.com)
     * @return array
     */
    public function getProjectBannerInfo($params){
        $pic_model = new ProjectPicture();
        $list = $pic_model->find()->select('*')->where(['project_id'=>$params['project_id'],'deleted_at'=>null])->asArray()->all();//项目海报
        return empty($list)?array():$list;
    }

    /**
     * 获取项目视频
     * @param $params
     * @author hey_heyang(635870453@qq.com)
     * @return array
     */
    public function getProjectVideoInfo($params){
        $video_model = new ProjectVideo();
        $list = $video_model->find()->select('*')->where(['project_id'=>$params['project_id'],'deleted_at'=>null])->asArray()->all();//项目视频
        return empty($list)?array():$list;
    }

    /**
     * 获取项目动态资讯
     * @param $params
     * @author hey_heyang(635870453@qq.com)
     * @return array
     */
    public function getProjectInformationInfo($params){
        $model = new Information();
        $list= $model->find()->select('*,FROM_UNIXTIME(created_at) as created_at')->where(['project_id'=>$params['project_id'],'deleted_at'=>null,'status'=>1])->asArray()->all();//项目相关资讯动态
//        $list['information_list_num'] = count($list['information_list']);
        return empty($list)?array():$list;
    }



    /**
     * 获取项目首页电影分类列表
     * @param $params
     * @author hey_heyang(635870453@qq.com)
     * @return array
     */
    public function getIndexProjectInfo($params){
        $condition = ['new_project.deleted_at'=>null,'new_project.status'=>1];
        $list = (new Query())->select(
            'new_project.*,
            project_class.title as class_name,
            project_class.info as class_info,
            project_class.sort as class_sort,
            project_class.id as class_id,
            FROM_UNIXTIME(new_project.created_at) as created_at'
            )
            ->from('new_project')
            ->innerJoin('project_class','project_class.id=new_project.class_id')
            ->where($condition)
            ->orderBy('class_sort ASC')
            ->all();
        if(count($list)){
            $data_list=array();
            foreach($list as $k=>$v){
                if(empty( $data_list[$v['class_id']]['class_name'])){
                    $data_list[$v['class_id']]['class_name']=$v['class_name'];
                    $data_list[$v['class_id']]['class_info']=$v['class_info'];
                    $data_list[$v['class_id']]['class_id']=$v['class_id'];
                }
              $data_list[$v['class_id']]['list'][]=$v;
            }
            foreach($data_list as $key=>$value){
                $data_list[$key]['list'] = array_slice($value['list'],0,6);
            }
        }

        return empty($data_list)?array():array_values($data_list);

    }


    /**
     * 获取某项目首页电影分类列表
     * @param $params
     * @author hey_heyang(635870453@qq.com)
     * @return array
     */
    public function getTargetProjectList($params){
        $condition = ['new_project.deleted_at'=>null,'new_project.status'=>1];
        if(!empty($params['class_id'])){
            $condition['new_project.class_id'] = intval($params['class_id']);
        }
        if(!empty($params['is_recommend'])){
            $condition['new_project.is_recommend'] = intval($params['is_recommend']);
        }
        $list = (new Query())->select(
            'new_project.*,
            project_class.title as class_name,
            FROM_UNIXTIME(new_project.created_at) as created_at'
        )
            ->from('new_project')
            ->leftJoin('project_class','project_class.id=new_project.class_id')
            ->where($condition)
            ->all();

        return empty($list)?array():$list;

    }


    /**
     * 获取项目相关帖子列表
     * @param $params
     * @author hey_heyang(635870453@qq.com)
     * @return array
     */
    public function getProjectPostsList($params){
        $condition = ['and','new_project.status=1',['new_project.id'=>intval($params['project_id'])],['new_project.deleted_at'=>null,'posts.status'=>3,'posts.deleted_at'=>null]];
        $list = (new Query())
            ->select('posts.*,member.username as username,member.head_img,FROM_UNIXTIME(posts.created_at) as created_at'
            )
            ->from('new_project')
            ->leftJoin('posts_join','posts_join.item_id=new_project.id')
            ->leftJoin('posts','posts_join.posts_id=posts.id')
            ->leftJoin('member','member.id=posts.set_posts_id')
            ->where($condition)
            ->orderBy('posts.id desc')
            ->all();
        $list = tools::getPageData($list,empty($params['page_size'])?'':$params['page_size'],empty($params['page'])?'':$params['page']);
        if(count($list['data'])){
            $comment_model =new \frontend\models\Comment();
            $posts_collect_model =new \frontend\models\PostsCollect();
            foreach($list['data'] as &$value){  // 处理帖子相关的评论、点赞、收藏数据
                $value['img'] = explode(',',$value['img']);
                $value['comment_num'] = $comment_model->find()->where(['posts_id'=>$value['id'],'deleted_at'=>null,'status'=>3])->asArray()->count();
                $value['like_num'] = $posts_collect_model->find()->where(['posts_id'=>$value['id'],'deleted_at'=>null,'is_like'=>1])->asArray()->count();
                $value['collect_num'] = $posts_collect_model->find()->where(['posts_id'=>$value['id'],'deleted_at'=>null,'is_collect'=>1])->asArray()->count();
                if(!empty($params['member_id'])){
                    $info = $posts_collect_model->find()->where(['posts_id'=>$value['id'],'member_id'=>$params['member_id'],'deleted_at'=>null])->asArray()->one();
                    $value['is_like'] = (empty($info['is_like']) || $info['is_like']==2) ? 2 : 1;
                    $value['is_collect'] = (empty($info['is_collect']) || $info['is_collect']==2) ? 2 : 1;
                }else{
                    $value['is_like'] =  2;
                    $value['is_collect'] = 2;
                }

            }
        }
        return empty($list)?array():$list;

    }



    /**
     * 获取首页搜索结果列表
     * @param $params
     * @param $member_info
     * @author hey_heyang(635870453@qq.com)
     * @return array
     */
    public function getIndexSearchList($params,$member_info){
        $list=[];
        if(empty($params['type']) || $params['type']==0){ //全部
            $project_list = $this->getSearchProjectList($params);
            $group_list = $this->getSearchGroupList($params,$member_info);
            $posts_list = $this->getSearchPostsList($params,$member_info);
            $list=array_merge($project_list,$group_list,$posts_list);
        }elseif($params['type']==1){ //项目
            $list = $this->getSearchProjectList($params);
        }elseif($params['type']==2){// 群组(此处需要判断用户是否登录,如果登录则判断是否满足进入群组的条件)
            $list = $this->getSearchGroupList($params,$member_info);
        }elseif($params['type']==3){// 帖子
            $list = $this->getSearchPostsList($params,$member_info);
        }
        return empty($list)?array():$list;

    }

    /**
     * 获取搜索项目列表
     * @param $params
     * @author hey_heyang(635870453@qq.com)
     * @return array
     */
    public function getSearchProjectList($params){
        $condition = ['new_project.status'=>1,'new_project.deleted_at'=>null];
        if(!empty($params['keyword'])){
            $condition = ['and','new_project.status=1',['like','new_project.title',trim($params['keyword'])],['new_project.deleted_at'=>null]];
        }
        $list = (new Query())
            ->select('new_project.id,
                    new_project.pic,
                    new_project.title ,
                    new_project.is_recommend,
                    new_project.tags,
                    new_project.introduction,
                    new_project.click_num,
                    project_class.title as class_name,
                    FROM_UNIXTIME(new_project.created_at) as created_at,
                    FROM_UNIXTIME(new_project.release_time) as release_time'
            )
            ->from('new_project')
            ->leftJoin('project_class','project_class.id=new_project.class_id')
            ->where($condition)
            ->orderBy('new_project.id desc')
            ->all();
        if(count($list)){
            $actor_model = new ProjectActor();
            $tags_model = new ProjectType();
            $posts_collect_model =new \frontend\models\PostsCollect();
            foreach($list as &$value){
                $value['search_type']=1; //项目
                $actor_list =$actor_model->find()->select('*')->where(['project_id'=>$value['id'],'deleted_at'=>null])->asArray()->all();
                $value['actor_list'] = $actor_list;
                $tags = unserialize($value['tags']);
                $value['tags'] =$tags_model->find()->select('title')->where(['in','id',$tags])->asArray()->all(); //项目标签类型
                $value['collect_num'] = $posts_collect_model->find()->where(['item_id'=>$value['id'],'deleted_at'=>null,'is_collect'=>1])->asArray()->count();
                $info = $posts_collect_model->find()->where(['item_id'=>$value['id'],'deleted_at'=>null])->asArray()->one();
                $value['is_like'] = (empty($info['is_like']) || $info['is_like']==2) ? 2 : 1;
                $value['is_collect'] = (empty($info['is_collect']) || $info['is_collect']==2) ? 2 : 1;
            }
        }
        return empty($list)?array():$list;

    }

    /**
     * 获取搜索群组列表
     * @param $params
     * @param $member_info
     * @author hey_heyang(635870453@qq.com)
     * @return array
     */
    public function getSearchGroupList($params,$member_info){
        $condition = ['deleted_at'=>null];
        if(!empty($params['keyword'])){
            $condition = ['and',['like','name',trim($params['keyword'])],['deleted_at'=>null]];
        }
        $list = (new Query())
            ->select('id as group_id,describe,cover,name,experience,project_id')
            ->from('group')
            ->where($condition)
            ->orderBy('is_recommend desc,id desc')
            ->all();
        if(count($list)){
            $actor_model = new GroupMember();
            foreach($list as &$value){
                $value['search_type']=2; //群组
                $total_num =$actor_model->find()->where(['group_id'=>$value['group_id'],'deleted_at'=>null])->asArray()->count();
                $value['total_num'] = $total_num;
                if(!empty($member_info['id'])){
                    // 补充判断是否能够加入群组
                    $member_join_group = $actor_model->find()->where(['group_id'=>$value['group_id'],'member_id'=>intval($member_info['id']),'deleted_at'=>null])->asArray()->one();
                    if(empty($member_join_group)){
                        $value['is_add'] = 'yes';
                    }else{
                        $value['is_add'] = 'no';
                    }

                }
            }
        }
        return empty($list)?array():$list;

    }


    /**
     * 获取搜索帖子列表
     * @param $params
     * @param $member_info
     * @author hey_heyang(635870453@qq.com)
     * @return array
     */
    public function getSearchPostsList($params,$member_info){
        $list=[];
        $condition=['posts.deleted_at'=>null,'posts.status'=>3];
        if(!empty($params['keyword'])){
            $condition=['and',['posts.deleted_at'=>null,'posts.status'=>3],['like','posts.title',$params['keyword']]];
            }
            $list = (new Query())->select(
                'posts.id as posts_id,posts.img as posts_img,posts.title as posts_title,posts.describe as posts_describe,FROM_UNIXTIME(posts.created_at) as created_at,
                 member.username as username, member.head_img'
            )
                ->from('posts')
                ->innerJoin('member','member.id=posts.set_posts_id')
                ->where($condition)
                ->orderBy('posts.id desc')
                ->all();
            if(count($list)){
                $comment_model =new comment_model();
                $posts_collect_model =new p_collect_model();
                foreach($list as &$value){  // 处理帖子相关的评论、点赞、收藏数据
                    $value['posts_img']=explode(',',$value['posts_img']);
                    $value['search_type']=3; //帖子
                    $value['comment_num'] = $comment_model->find()->where(['posts_id'=>$value['posts_id'],'deleted_at'=>null,'status'=>3])->asArray()->count();
                    $value['like_num'] = $posts_collect_model->find()->where(['posts_id'=>$value['posts_id'],'deleted_at'=>null,'is_like'=>1])->asArray()->count();
                    $value['collect_num'] = $posts_collect_model->find()->where(['posts_id'=>$value['posts_id'],'deleted_at'=>null,'is_collect'=>1])->asArray()->count();
                    if(!empty($member_info['id'])){
                        $info = $posts_collect_model->find()->where(['posts_id'=>$value['posts_id'],'member_id'=>$member_info['id'],'deleted_at'=>null])->asArray()->one();
                        $value['is_like'] = (empty($info['is_like']) || $info['is_like']==2) ? 2 : 1;
                        $value['is_collect'] = (empty($info['is_collect']) || $info['is_collect']==2) ? 2 : 1;
                    }else{
                        $value['is_like'] =2;
                        $value['is_collect'] =2;
                    }


                    }

                }

        return empty($list)?array():$list;
    }


    /**
     * 获取是否可以加入群组
     * @param $params
     * @param $member_info
     * @author hey_heyang(635870453@qq.com)
     * @return array
     */
    public function getAuthJoinGroup($params,$member_info){
        $model = new Group();
        if(!empty($member_info['id']) && !empty($params['group_id'])){
            $list['is_add'] = 'yes';
            // 补充判断是否能够加入群组
          $group_info = $model->find()->where(['id'=>intval($params['group_id']),'deleted_at'=>null])->asArray()->one();
            if(empty($group_info)) return ['error'=>"群组已失效!"];
            if(!empty($group_info['experience'])){ //入群经验值
                if(intval($member_info['experience'])<intval($group_info['experience'])){
                    $list['is_add'] = 'no';
                }
            }
            if(!empty($group_info['project_id'])){ //入群认投项目
//                $project_order_info =  (new Query())->from('tf_order')->where(['uid'=>intval($member_info['id']),'project_id'=>intval($group_info['project_id']),'status'=>2])->one();
                if(empty($member_info['hry_member_id'])){
                    $list['is_add'] = 'no';
                }else{
                    $hryModel =new HryOrder();
                    $project_order_info = $hryModel->getHryMemberOrder(intval($group_info['project_id']),intval($member_info['hry_member_id']));
                    if(empty($project_order_info['id'])){
                        $list['is_add'] = 'no';
                    }
                }

            }
            return $list['is_add'];
        }else{
            return ['error'=>"参数错误!"];
        }


    }


    /**
     * 获取首页票房数据
     * @author hey_heyang(635870453@qq.com)
     * @return array
     */
    public function getMovieBoxOffice(){
        $curl = curl_init(); //初始化
        curl_setopt($curl, CURLOPT_URL, 'http://piaofang.maoyan.com/second-box'); // 要访问的地址
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); // 从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 直接返回数据
        curl_setopt($curl, CURLOPT_HTTPHEADER, array('Expect:'));
        $data = curl_exec($curl);
        $data=json_decode($data,true);
        return empty($data)?array():$data;

    }



}
